package com.ltu.config.shiro.realm;

import com.ltu.base.State;
import com.ltu.constant.CommonConstant;

import java.util.Arrays;
import java.util.Objects;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.ltu.config.shiro.ShiroUserService;
import com.ltu.config.shiro.dto.MyUsernamepwdToken;
import com.ltu.config.shiro.dto.UserDto;
import com.ltu.util.exception.ApiException;

/**
 * @Description:
 * @author: 若尘
 * @date 2019年9月16日 下午5:16:20
 * @version V1.0
 */
public class DbShiroRealm extends AuthorizingRealm {

	private ShiroUserService shiroUserService;

	public DbShiroRealm() {
		// Auto-generated constructor stub
	}

	/**
	 * @param shiroUserService
	 */
	public DbShiroRealm(ShiroUserService shiroUserService) {
		// Auto-generated constructor stub
		this.shiroUserService = shiroUserService;
//		this.setCredentialsMatcher(new SimpleCredentialsMatcher());
	}

	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof UsernamePasswordToken;
	}

	/*
	 * (non-Javadoc) 登录认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {

		MyUsernamepwdToken userToken = (MyUsernamepwdToken) token;
		UserDto user = null;
		if (userToken.getAccountType() == CommonConstant.LOGIN_TYPE_BACKSTAGE) {
			
			user = shiroUserService.getAccountInfo(userToken.getUsername());
			
		}
	
		if (Objects.equals(CommonConstant.USER_FRONT_TYPE_NORMAL, userToken.getFrontType()))// 客户登录
				user = shiroUserService.getUserByopenId(userToken.getUsername(), userToken.getFrontType());
		if (user == null)
			throw new AuthenticationException("用户不存在");

		if (user.getEnable() == 0)
			throw new ApiException(State.USERBAN);

		return new SimpleAuthenticationInfo(user, user.getPassword(), "dbRealm");
	}



	/*
	 * doGetAuthenticationInfo 登录成功后
	 * (non-Javadoc) 获取用的角色
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		SimpleAuthorizationInfo simpleAuthenticationInfo = new SimpleAuthorizationInfo();
		UserDto user = (UserDto) principals.getPrimaryPrincipal();

		if (user.getRoles() == null && user.getLoginType() == CommonConstant.LOGIN_TYPE_BACKSTAGE) {
			user.setRoles(shiroUserService.getAccountRoles(user.getId(), user.getFrontType()));
		}
		if (user.getRoles() != null) {
			simpleAuthenticationInfo.addRoles(user.getRoles());
		}
		return simpleAuthenticationInfo;
	}
}
